<template>

    <el-main>
      <!-- 搜索与操作区域 -->
      <el-form :inline="true">
        <el-form-item label="客户姓名"><el-input v-model="filters.clientName" placeholder="姓名" clearable/></el-form-item>
        <el-form-item label="入住日期"><el-date-picker v-model="filters.bedBeginTime" type="date" placeholder="选择开始日期" style="width:150px"/></el-form-item>
        <el-form-item label="结束日期"><el-date-picker v-model="filters.bedEndTime" type="date" placeholder="选择结束日期" style="width:150px"/></el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="success" @click="onReset">重置</el-button>
<!--          <el-button  type="danger" @click="onDeleteAll">一键删除</el-button>-->
          <el-button style="margin-left: 100px;" type="warning" @click="confirmExport">导出</el-button>
        </el-form-item>
      </el-form>

      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-radio-group v-model="filters.bedRecordStatus" @change="onSearch">
            <el-radio-button :label="1">正在使用</el-radio-button>
            <el-radio-button :label="0">历史记录</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" style="width: 100%">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="clientName" label="客户姓名" />
        <el-table-column prop="bedId" label="床位ID" />
        <el-table-column prop="bedCode" label="床位编号" />
        <el-table-column prop="roomId" label="房间号" />
        <el-table-column prop="floorId" label="楼层号" />
        <el-table-column prop="bedBeginTime" label="使用开始时间" :formatter="formatDateTime"/>
        <el-table-column prop="bedEndTime" label="使用结束时间" :formatter="formatDateTime"/>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="warning" @click="openEditDialog(scope.row)" :disabled="scope.row.bedRecordStatus === 0">修改</el-button>
            <el-button type="danger" @click="openSwapDialog(scope.row)" :disabled="scope.row.bedRecordStatus === 0">调换</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" style="margin-top: 20px; display: flex; justify-content: flex-end;">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[6, 10, 20, 50]"
            @current-change="handlePageChange"
            @size-change="handleSizeChange">
        </el-pagination>
      </div>

      <!-- 修改对话框 -->
      <el-dialog v-model="editDialog.visible" title="修改床位使用结束时间" width="400px">
        <el-form label-width="110px"><el-form-item label="结束时间"><el-date-picker v-model="editDialog.endTime" type="datetime" style="width:100%" /></el-form-item></el-form>
        <template #footer><el-button @click="editDialog.visible=false">取消</el-button><el-button type="primary" @click="submitEdit" :loading="editDialog.loading">确认</el-button></template>
      </el-dialog>

      <!-- 调换对话框 (已修改) -->
      <el-dialog v-model="swapDialog.visible" title="床位调换" width="500px">
        <el-form ref="swapFormRef" :model="swapForm" :rules="swapFormRules" label-width="110px" v-loading="swapDialog.loading">
          <el-form-item label="当前客户"><strong>{{ swapDialog.clientName }}</strong></el-form-item>
          <el-form-item label="当前床位">{{ swapDialog.currentBedInfo }}</el-form-item>
          <el-divider />
          <el-form-item label="选择新楼层">
            <el-select v-model="swapForm.selectedFloor" placeholder="请选择楼层" @change="handleSwapFloorChange" style="width:100%">
              <el-option v-for="f in swapData.floors" :key="f" :label="`${f}层`" :value="f" />
            </el-select>
          </el-form-item>
          <el-form-item label="选择新房间">
            <el-select v-model="swapForm.selectedRoom" placeholder="请先选择楼层" @change="handleSwapRoomChange" style="width:100%" :disabled="!swapForm.selectedFloor">
              <el-option v-for="r in swapData.rooms" :key="r" :label="`${r}室`" :value="r" />
            </el-select>
          </el-form-item>
          <el-form-item label="选择新床位" prop="newBedId">
            <el-select v-model="swapForm.newBedId" placeholder="请先选择房间" style="width:100%" :disabled="!swapForm.selectedRoom">
              <el-option v-for="b in swapData.beds" :key="b.bedId" :label="b.bedCode" :value="b.bedId" />
            </el-select>
          </el-form-item>
          <!-- 新增：让用户选择新记录的开始和结束时间 -->
          <el-form-item label="新开始时间" prop="newBeginTime">
            <el-date-picker v-model="swapForm.newBeginTime" type="datetime" placeholder="选择新记录的开始时间" style="width:100%" />
          </el-form-item>
          <el-form-item label="新结束时间" prop="newEndTime">
            <el-date-picker v-model="swapForm.newEndTime" type="datetime" placeholder="新记录的结束时间" style="width:100%" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="swapDialog.visible=false">取消</el-button>
          <el-button type="primary" @click="submitSwap" :loading="swapDialog.loading">确认调换</el-button>
        </template>
      </el-dialog>

    </el-main>

</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { listBedRecords, updateBedRecord, swapBed } from '@/api/apiList/bedRecord.js';
import { getFloors, getAvailableBedsByFloor } from '@/api/apiList/bed.js';

// --- 通用状态 ---
const loading = ref(false);
const tableData = ref([]);
const filters = reactive({ clientName: '', bedBeginTime: null, bedEndTime: null, bedRecordStatus: 1 });
const pagination = reactive({ total: 0, currentPage: 1, pageSize: 6 });

// --- 修改对话框状态 ---
const editDialog = reactive({ visible: false, loading: false, recordId: null, endTime: null });

// --- 调换对话框状态 ---
const swapDialog = reactive({ visible: false, loading: false, clientName: '', currentBedInfo: '' });
const swapFormRef = ref(null);
const swapForm = reactive({
  oldBedId: null,
  newBedId: null,
  selectedFloor: null,
  selectedRoom: null,
  newBeginTime: null,
  newEndTime: null,
});
const swapFormRules = reactive({
  newBedId: [{ required: true, message: '请选择一个新的床位', trigger: 'change' }],
  newBeginTime: [{ required: true, message: '请选择新记录的开始时间', trigger: 'change' }],
});
const swapData = reactive({
  floors: [],
  availableBedMap: {},
  rooms: [],
  beds: [],
});


// --- 方法 ---
const formatDateTime = (r,c,v) => v ? new Date(v).toLocaleString() : '---';

async function fetchData() {
  loading.value = true;
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      clientName: filters.clientName,
      bedBeginTime: filters.bedBeginTime,
      bedRecordStatus: filters.bedRecordStatus,
      bedEndTime: filters.bedEndTime
    };
    const pageData = await listBedRecords(params);
    // console.log(pageData);
    tableData.value = pageData.records;
    pagination.total = pageData.total;
  } catch(e) { console.error("获取床位记录失败:", e); }
  finally { loading.value = false; }
}
function handlePageChange(newPage) {
  pagination.currentPage = newPage;
  fetchData();
}

function handleSizeChange(newSize) {
  pagination.pageSize = newSize;
  pagination.currentPage = 1;
  fetchData();
}

const onSearch = () => { pagination.currentPage = 1; fetchData(); }
const onReset = () => {
  filters.clientName = '';
  filters.bedBeginTime = null;
  filters.bedEndTime = null;
  filters.bedRecordStatus = 1;
  onSearch();
}

function openEditDialog(row) {
  editDialog.recordId = row.bedRecordId;
  editDialog.endTime = new Date(); // 默认填充当前时间
  editDialog.visible = true;
}
async function submitEdit() {
  if (!editDialog.endTime) { ElMessage.warning("请选择结束时间"); return; }
  editDialog.loading = true;
  try {
    await updateBedRecord({ bedRecordId: editDialog.recordId, bedEndTime: editDialog.endTime });
    ElMessage.success('修改成功');
    editDialog.visible = false;
    fetchData();
  } catch(e) { console.error(e); }
  finally { editDialog.loading = false; }
}

// 新增：日期格式化辅助函数，用于将Date对象转为"yyyy-MM-dd HH:mm:ss"字符串
const formatDateTimeForApi = (date) => {
  if (!date) return null;
  const d = new Date(date);
  const pad = (num) => num.toString().padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
async function openSwapDialog(row) {
  // 重置表单状态
  if (swapFormRef.value) swapFormRef.value.clearValidate();
  Object.assign(swapForm, {
    oldBedId: row.bedId,
    newBedId: null,
    selectedFloor: null,
    selectedRoom: null,
    newBeginTime: new Date(), // 默认填充当前时间
    newEndTime: null
  });
  Object.assign(swapData, { floors: [], availableBedMap: {}, rooms: [], beds: [] });

  swapDialog.clientName = row.clientName;
  swapDialog.currentBedInfo = `${row.floorId}层 - ${row.roomId}室 - ${row.bedCode}`;
  swapDialog.visible = true;

  try {
    swapData.floors = await getFloors();
  } catch (e) {
    console.error("获取楼层列表失败:", e);
  }
}

async function submitSwap() {
  if (!swapFormRef.value) return;
  await swapFormRef.value.validate(async (valid) => {
    if (valid) {
      swapDialog.loading = true;
      try {
        // 准备提交给后端的数据
        const swapDataPayload = {
          oldBedId: swapForm.oldBedId,
          newBedId: swapForm.newBedId,
          // 使用辅助函数格式化日期
          newBeginTime: formatDateTimeForApi(swapForm.newBeginTime),
          newEndTime: formatDateTimeForApi(swapForm.newEndTime)
        };
        await swapBed(swapDataPayload);
        ElMessage.success('床位调换成功');
        swapDialog.visible = false;
        fetchData();
      } catch(e) { console.error("床位调换失败:", e); }
      finally { swapDialog.loading = false; }
    }
  });
}


async function handleSwapFloorChange(floorId) {
  // 清空下游选择
  swapForm.selectedRoom = null;
  swapForm.newBedId = null;
  swapData.rooms = [];
  swapData.beds = [];
  if (!floorId) return;

  try {
    swapData.availableBedMap = await getAvailableBedsByFloor(floorId);
    swapData.rooms = Object.keys(swapData.availableBedMap);
    if (swapData.rooms.length === 0) {
      ElMessage.warning("该楼层暂无空闲房间");
    }
  } catch (e) { console.error(e); }
}

function handleSwapRoomChange(roomId) {
  swapForm.newBedId = null;
  swapData.beds = swapData.availableBedMap[roomId] || [];
}

onMounted(fetchData);
</script>

<style scoped>
.pagination-container { margin-top: 20px; display: flex; justify-content: flex-end; }
</style>
